//
//  UIControl+HitEdgeInsets.m
//  ITC_iOS
//
//  Created by iBenz on 2018/9/1.
//  Copyright © 2018年 Benz.L. All rights reserved.
//

#import "UIControl+HitEdgeInsets.h"
#import <objc/runtime.h>

const char kHitEdgeInsetsKey = '\0';

@implementation UIButton(HitEdgeInsets)
@dynamic hitEdgeInsets;

- (void)setHitEdgeInsets:(UIEdgeInsets)hitEdgeInsets {
    NSValue *value = [NSValue valueWithUIEdgeInsets:hitEdgeInsets];
    objc_setAssociatedObject(self, &kHitEdgeInsetsKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIEdgeInsets)hitEdgeInsets {
    NSValue *value = objc_getAssociatedObject(self, &kHitEdgeInsetsKey);
    if(value) {
        return [value UIEdgeInsetsValue];
    }else {
        return UIEdgeInsetsZero;
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if(UIEdgeInsetsEqualToEdgeInsets(self.hitEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
        return [super pointInside:point withEvent:event];
    }
    
    CGRect relativeFrame = self.bounds;
    CGRect hitFrame = relativeFrame;
    hitFrame.origin.x = relativeFrame.origin.x-self.hitEdgeInsets.left;
    hitFrame.origin.y = relativeFrame.origin.y - self.hitEdgeInsets.top;
    hitFrame.size.width += (self.hitEdgeInsets.left+self.hitEdgeInsets.right);
    hitFrame.size.height += (self.hitEdgeInsets.top+self.hitEdgeInsets.bottom);
    //CGRect hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitEdgeInsets);
    
    return CGRectContainsPoint(hitFrame, point);
}
@end
